<?php

namespace App\Http\Controllers\Guard\Shop;

use App\Http\Controllers\Common\GuardController;
use App\Models\Shop\Goods\GoodsClassify;
use App\Models\Shop\Goods\GoodsSku;
use App\Models\Shop\Goods\GoodsSpu;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class GoodsSpuController extends GuardController {

    public function lst(Request $request) {
        $conditions = $request->input();

        if(!empty($conditions['selectClassifyId']) && count($conditions['selectClassifyId'])>0){
            $conditions['selectClassifyId'] = array_pop($conditions['selectClassifyId']);
        }

        $page = $request->input('page',1);
        $pageSize = $request->input('pageSize',20);
        $records = (new GoodsSpu())->getLst($conditions)->with(['getClassify:id,name','getBrand:id,name'])->paginate($pageSize,['*'],'page',$page);

        foreach ($records as $record) {
            $record->desc_detail = Str::limit($record->desc_detail,30);
        }

        return responseSuccess($records->items(),$records->total());
    }

    public function add(Request $request) {
        $spuInfo = $request->input('spuInfo',[]);
        $selectClassifyId = $request->input('selectClassifyId',[]);
        $is_single = $spuInfo['is_single']??1;
        $this->validate($request, [
            'spuInfo.name'=>'required',
            'spuInfo.brand_id'=>'required|integer|gte:0',
            'spuInfo.desc_detail'=>'required',
            'spuInfo.cover_urls'=>'required|array|min:1',
        ],[],[
            'spuInfo.name'=>'商品名称',
            'spuInfo.brand_id'=>'品牌id',
            'spuInfo.desc_detail'=>'商品详情',
            'spuInfo.cover_urls'=>'商品封面',
        ]);
        $classify_id = array_pop($selectClassifyId)??0;

        $spuInfo['cover_urls'] = implode(',', array_column($spuInfo['cover_urls'], 'url') );
        $spuInfo = array_merge($spuInfo,compact('classify_id'));
        //单规格
        if($is_single==1){
            GoodsSpu::updateOrCreate(['id'=>$spuInfo['id']??0],$spuInfo);
            return responseSuccess();
        }
        //双规格
        else{
            $skuInfo = $request->input('skuInfo',[]);
            try {
                DB::beginTransaction();
                $spu = GoodsSpu::updateOrCreate(['id'=>$spuInfo['id']??0],$spuInfo);
                if(count($skuInfo)>0){
                    foreach ($skuInfo as &$item) {
                        $item['classify_last_id'] = $classify_id;
                        $item['spu_id'] = $spu->id;
                        $item['updated_at'] = $item['created_at'] = date('Y-m-d H:i:s');
                    }
                    GoodsSku::insert($skuInfo);
                }
                DB::commit();
                return responseSuccess();
            }catch (\Exception $e){
                DB::rollBack();
                $tip = $e->getFile().':'.$e->getLine().':'.$e->getMessage();
                return responseFail($tip);
            }
        }

    }

    public function changeStatus(Request $request) {
        $id = $request->input('id',0);
        $status = $request->input('status',1);
        $this->changeCol(GoodsSpu::class, ['id'], [$id],['status'], [$status]);
        return responseSuccess();
    }

    public function detail(Request $request) {
        $id = $request->input('id',0);
        $record = GoodsSpu::where(compact('id'))->with('getSku')->first();
        $imgs = array_filter(explode(',', $record->cover_urls));
        $temp = [];
        foreach ($imgs as $img){
            $temp[] = [
                'uid'=>uniqid(),
                'path'=>$img,
                'url'=>asset($img)
            ];
        }
        $record->cover_urls = $temp;
        $classify = GoodsClassify::find($record->classify_id);
        $grandFatherClassify = GoodsClassify::find($classify->pid)->id??0;
        $temp =[];
        if($grandFatherClassify!=0)
            $temp[] = $grandFatherClassify;
        if($classify->pid!=0)
            $temp[] = $classify->pid;
        if($classify->id!=0)
            $temp[] = $classify->id;

        $record->all_classify_ids = array_unique($temp);
        return responseSuccess($record->toArray());

    }

}
